package com.lishe.lishe.lishe.module.excitation.fragment;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fynn.fluidlayout.FluidLayout;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.ImageSelector.ImageObject;
import com.lishe.lishe.lishe.ImageSelector.ImageSelectorActivity;
import com.lishe.base.common.base.BaseFragment;
import com.lishe.lishe.lishe.bean.GiftObject;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.excitation.activity.DianZanPersonActivity;
import com.lishe.lishe.lishe.module.excitation.activity.DianZanReasonActivity;
import com.lishe.lishe.lishe.module.excitation.activity.SelectGiftActivity;
import com.lishe.lishe.lishe.module.excitation.activity.VisualRangeActivity;
import com.lishe.lishe.lishe.module.excitation.bean.LabelObject;
import com.lishe.lishe.lishe.module.excitation.bean.user.UserObject;
import com.lishe.lishe.lishe.module.excitation.http.HttpExcitation;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.PermissionUtils;
import com.lishe.lishe.lishe.utils.StringUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;


/**
 * Created by shino on 2017/10/21.
 * 发起点赞
 */

public class SendDianZanFragment extends BaseFragment implements View.OnClickListener {

    private Button callBack;
    private Button send;
    private TextView title;
    private LinearLayout nameLayout;
    private LinearLayout giftLayout;
    private LinearLayout seedLayout;
    private FluidLayout imageLayout;
    private RelativeLayout noteLayout;
    private TextView name;
    private TextView note;
    private TextView textCount;
    private TextView gift;
    private TextView seed;
    private EditText content;
    private ImageView addImage;
    //发起点赞上传参数
    private GiftObject giftObject;//小礼
    private LabelObject label;//label
    private UserObject dianzanUsre;//点赞对象
    private int showScope = 1;//可视范围 1：全公司，2：我所在部门 3：他所在部门
    private List<ImageObject> imageObjects = new ArrayList<>();
    private List<String> filePath = new ArrayList<>();//图片地址列表


    public static SendDianZanFragment newInstance() {
        SendDianZanFragment fragment = new SendDianZanFragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_send_dianzan, null);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View v) {
        callBack = v.findViewById(R.id.title_left_button);
        send = v.findViewById(R.id.send);
        title = v.findViewById(R.id.title_text_title);
        nameLayout = v.findViewById(R.id.name_layout);
        giftLayout = v.findViewById(R.id.gift_layout);
        seedLayout = v.findViewById(R.id.seed_layout);
        noteLayout = v.findViewById(R.id.note_layout);
        imageLayout = v.findViewById(R.id.image_layout);
        name = v.findViewById(R.id.name);
        note = v.findViewById(R.id.note);
        textCount = v.findViewById(R.id.textCount);
        gift = v.findViewById(R.id.gift);
        seed = v.findViewById(R.id.seed);
        content = v.findViewById(R.id.content);
        addImage = v.findViewById(R.id.add_image);
        title.setText("发起点赞");
        seed.setText("全公司范围");
        setListener();
    }

    private void setListener() {
        callBack.setOnClickListener(this);
        send.setOnClickListener(this);
        nameLayout.setOnClickListener(this);
        giftLayout.setOnClickListener(this);
        seedLayout.setOnClickListener(this);
        noteLayout.setOnClickListener(this);
        addImage.setOnClickListener(this);
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String charSequence = editable.toString().trim();
                content.setTextColor(getResources().getColor(R.color.gray_3));
                if (charSequence.length() > 140) {
                    String str = charSequence.length() + "/140";
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(str);
                    int index = str.indexOf("/140");
                    stringBuilder.setSpan(new ForegroundColorSpan(Color.RED), 0, index, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    textCount.setText(stringBuilder);
                    String text = charSequence.toString();
                    SpannableStringBuilder stringBuilder0 = new SpannableStringBuilder(text);
                    stringBuilder0.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.gray_9)), 140, charSequence.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    content.removeTextChangedListener(this);
                    content.setText(stringBuilder0);
                    content.setSelection(charSequence.length());
                    content.addTextChangedListener(this);
                } else {
//                    content.removeTextChangedListener(this);
//                    content.setTextColor(getResources().getColor(R.color.gray_3));
//                    content.setText(editable.toString());
//                    content.setSelection(charSequence.length());
//                    content.addTextChangedListener(this);
                    textCount.setText(charSequence.length() + "/140");
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                getFragmentManager().popBackStack();
                break;
            case R.id.name_layout://点赞对象
                DianZanPersonActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_DianZanPersonActivity);
                break;
            case R.id.gift_layout://赠送小礼
                SelectGiftActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_SelectGiftActivity);
                break;
            case R.id.note_layout://为什么赞Ta
                DianZanReasonActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_DianZanReasonActivity);
                break;
            case R.id.seed_layout://可视范围
                VisualRangeActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_VisualRangeActivity);
                break;
            case R.id.add_image:
                if (PermissionUtils.isStorageWritePermission(getActivity())) {//获取手机权限
                    ImageSelectorActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_ImageSelectorActivity, 3 - imageObjects.size());
                }
                break;
            case R.id.send://发表
                if (content.getText().toString().length() > 140) {
                    toast("分享内容不能多于140个字！");
                } else {
                    if (isSend()) {
                        if (filePath.size() != 0) {
                            upImageFile(filePath);
                        } else {
                            sendDianzan();
                        }
                    }
                }
                break;
        }
    }

    private boolean isSend() {
        String text = content.getText().toString();
        if (TextUtils.isEmpty(text)) {
            toast("请输入点赞内容！");
            return false;
        }
        if (dianzanUsre == null) {
            toast("请选择点赞对象！");
            return false;
        }
        if (label == null) {
            toast("请选择点赞标签！");
            return false;
        }
        if (showScope == -1) {
            toast("请选择可视范围！");
            return false;
        }
        return true;
    }

    /**
     * 发起点赞
     */
    private void sendDianzan() {
        String text = content.getText().toString();
        if (filePath.size() == 0) {
            LoadingUtils.createLoadingDialog(getActivity(), "正在发表...", true);
        }
        String giftId = null;
        if (giftObject != null) {
            giftId = giftObject.getGiftId();
        }
        HttpExcitation.sendDianZanEvent(Globals.getToken(), dianzanUsre.getUserId(), label.getActionId(), StringUtils.stringToUtf8(text), showScope + "", giftId, imageObjects, dianzanResponse);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
        Log.e("onActivityResult", "有数据" + requestCode + "--" + resultCode);
        if (resultCode == getActivity().RESULT_OK) {
            Log.e("onActivityResult", "RESULT_OK");
            switch (requestCode) {
                case Globals.REQUSE_CODE_VisualRangeActivity://可视范围
                    showScope = Integer.valueOf(data.getIntExtra("type", -1));
                    String str = "";
                    switch (showScope) {
                        case 1:
                            str = "全公司";
                            break;
                        case 2:
                            str = "我所在部门";
                            break;
                        case 3:
                            str = "Ta所在部门";
                            break;
                    }
                    seed.setText(str);
                    break;
                case Globals.REQUSE_CODE_SelectGiftActivity://选择小礼
                    giftObject = (GiftObject) data.getSerializableExtra("gift");
                    gift.setText(giftObject.getGiftName());
                    break;
                case Globals.REQUSE_CODE_DianZanReasonActivity://点赞label
                    label = (LabelObject) data.getSerializableExtra("label");
                    note.setText(label.getActionName());
                    note.setVisibility(View.VISIBLE);
                    break;
                case Globals.REQUSE_CODE_DianZanPersonActivity://点赞对象
                    dianzanUsre = (UserObject) data.getSerializableExtra("diazanPerson");
                    name.setText(dianzanUsre.getEmpName());
                    break;

                case Globals.REQUSE_CODE_ImageSelectorActivity://选择图片
                    imageObjects.addAll((List<ImageObject>) data.getSerializableExtra("data"));
                    if (imageObjects.size() >= 3) {
                        addImage.setVisibility(View.GONE);
                    }
                    filePath.clear();
                    for (int i = 0; i < imageObjects.size(); i++) {
                        filePath.add(imageObjects.get(i).getPath());
                    }
                    createImageView();
                    break;
            }
        }
    }

    private void createImageView() {
        imageLayout.removeAllViews();
        for (int i = 0; i < imageObjects.size(); i++) {
            Log.e("图片", imageObjects.get(i).getPath());
            final View imageItem = getActivity().getLayoutInflater().inflate(R.layout.item_image_cancle, null);
            ImageView image = imageItem.findViewById(R.id.img);
            ImageView cancle = imageItem.findViewById(R.id.cancle);
            ImageLoaderUtils.displayLocationImages(getActivity(), imageObjects.get(i).getPath(), image);
            final int finalI = i;
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    imageObjects.remove(finalI);
                    filePath.remove(finalI);
                    imageLayout.removeView(imageItem);
                    if (imageObjects.size() < 3) {
                        addImage.setVisibility(View.VISIBLE);
                    }
                    createImageView();
                }
            });
            imageLayout.addView(imageItem);
        }
    }

    private void upImageFile(List<String> path) {
        LoadingUtils.createLoadingDialog(getActivity(), "正在发表...", true);
        try {
//            HttpExcitation.upFile(Globals.getToken(), path, "upImageFile", this);
            HttpExcitation.upFile(Globals.getToken(), path, imageResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AsyncHttpResponseHandler imageResponse = new AsyncHttpResponseHandler() {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String data = new String(responseBody);
            Log.e("图片上传", data);
            try {
                JSONObject json = new JSONObject(data);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    JSONObject jsonData = json.optJSONObject("data");
                    String[] imageUrl = jsonData.optString("info").split(",");
                    for (int i = 0; i < imageUrl.length; i++) {
                        imageObjects.get(i).setUrl(imageUrl[i]);
                    }
                    sendDianzan();
                } else {
                    toast(json.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
        }
    };
    AsyncHttpResponseHandler dianzanResponse = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            LoadingUtils.closeDialog();
            String data = new String(responseBody);
            Log.e("发起点赞内容", data);
            try {
                JSONObject json = new JSONObject(data);
                if (json.optInt("errcode") == 0 && json.optInt("result") == 100) {
                    toast("成功发起点赞！");
                    getFragmentManager().popBackStack();
                } else {
                    toast(json.optString("msg"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            toast("网络或服务器异常！");
        }
    };

    /**
     * SD卡权限处理
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PermissionUtils.request_permission_camera: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    ImageSelectorActivity.jump(SendDianZanFragment.this, Globals.REQUSE_CODE_ImageSelectorActivity, 3 - imageObjects.size());
                } else {
                    // permission denied
                    // request failed
                }
                return;
            }
        }
    }
}
